package me.yh.tech.util;

import java.io.File;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * @Classname DynamicClassLoad 动态加载第三方jar
 * @Description TODO
 * @Date 2020/2/27 11:38
 * @Created by 86153
 */
public class DynamicClassLoad {
    public static void main(String[] args) throws Exception{
        /*args=new String[]{"file://E:/CompilerTest/test.jar","com.example.demo.entity.User"};
        System.out.println("start");
        load(args[0],args[1]);*/
        String path = "E:/CompilerTest/demo-0.0.1-SNAPSHOT.jar";
        loadJar(path);
        Class<?> aClass = Class.forName("com.example.demo.entity.User");
        Object instance = aClass.newInstance();
        Object strip = aClass.getDeclaredMethod("toString").invoke(instance);
        System.out.println(strip);
    }
    public static void load(String fileName, String processorName) {
        String filePath = fileName;
        Process processor = null;
        URL url=null;
        try {
            url = new URL(filePath);
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
            System.out.println("文件不存在");
        }
        URLClassLoader loader = new URLClassLoader(new URL[]{url},Thread.currentThread().getContextClassLoader());
        try {
            //Class<?> processorClass = loader.loadClass(processorName);
            //processor = (Process)processorClass.newInstance();
            //processor.display();
        } catch (Exception e) {
            System.out.println("创建业务类失败");
            e.printStackTrace();
        }
    }
    public static void loadJar(String jarPath) {
        File jarFile = new File(jarPath);
        // 从URLClassLoader类中获取类所在文件夹的方法，jar也可以认为是一个文件夹
        Method method = null;
        try {
            method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
        } catch (NoSuchMethodException | SecurityException e1) {
            e1.printStackTrace();
        }
        // 获取方法的访问权限以便写回
        boolean accessible = method.isAccessible();
        try {
            method.setAccessible(true);
            // 获取系统类加载器
            URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
            URL url = jarFile.toURI().toURL();
            method.invoke(classLoader, url);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            method.setAccessible(accessible);
        }
    }
}
